﻿using FreeSql;
using IMES.Common.Domain.KeepModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using Keep.API.Common.L.Dtos;
using MediatR;
using Org.BouncyCastle.Asn1.Ocsp;
using System.Security;

namespace Keep.API.Appliction.Command.DepartmentFile
{
    /// <summary>
    /// 部门级联处理器
    /// </summary>
    public class DepartmentCascaderHandler:IRequestHandler<DepartmentCascaderCommon, ResultT<DepartmentCascader>>
    {
        private readonly IBaseRepositorys<Department> _DepartmentRep;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="DepartmentRep"></param>
        public DepartmentCascaderHandler(IBaseRepositorys<Department> DepartmentRep)
        {
            _DepartmentRep = DepartmentRep;
        }
        public async Task<ResultT<DepartmentCascader>> Handle(DepartmentCascaderCommon request, CancellationToken cancellationToken)
        {
            var result = new ResultT<DepartmentCascader>() { Code = (int)CodeEnum.search };
            var list =  _DepartmentRep.GetAll().Where(c => c.ParentId == 0).ToList();
            List<DepartmentCascader> DepartmentCascaderDtos = new List<DepartmentCascader>();
            foreach (var item in list)
            {
                DepartmentCascader DepartmentCascaderDto = new DepartmentCascader();
                DepartmentCascaderDto.label = item.OrgName;
                DepartmentCascaderDto.value = item.OrgId;
                DepartmentCascaderDto.children = Cascader(item.OrgId);
                DepartmentCascaderDtos.Add(DepartmentCascaderDto);
            }
            result.Data = DepartmentCascaderDtos;
            return result;
        }
        public List<DepartmentCascader> Cascader(int parentId)
        {
            var list = _DepartmentRep.GetAll().Where(c => c.ParentId == parentId).ToList();
            List<DepartmentCascader> DepartmentCascaderDtos = new List<DepartmentCascader>();
            foreach (var item in list)
            {
                DepartmentCascader DepartmentCascaderDto = new DepartmentCascader();
                DepartmentCascaderDto.label = item.OrgName;
                DepartmentCascaderDto.value = item.OrgId;
                DepartmentCascaderDto.children = Cascader(item.OrgId);
                DepartmentCascaderDtos.Add(DepartmentCascaderDto);
            }

            return DepartmentCascaderDtos;
        }
    }
}
